﻿using AutoMapper;
using B.S.Databasic.Api.Read.Application.Command.Permission;
using B.S.Databasic.Domain.RBAC;
using B.S.Databasic.ErrorCode;
using B.S.Databasic.Infrastructure.Interface;
using MediatR;
using Microsoft.AspNetCore.Mvc;

namespace B.S.Databasic.Api.Read.Application.Handler.Permission
{
    /// <summary>
    /// 获取权限树
    /// </summary>
    public class GetPermissionsFromDatabaseTreeHandler : IRequestHandler<GetPermissionsFromDatabaseTreeCommand, ApiResult<List<PermissionTreeDTO>>>
    {
        private readonly ILogger<GetPermissionsFromDatabaseTreeHandler> _logger;
        private readonly IBaseRepository<PermissionModel> permissionRepo;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger">日志记录器</param>
        /// <param name="permissionRepo">权限仓储</param>
        /// <param name="mapper">映射器</param>
        public GetPermissionsFromDatabaseTreeHandler(ILogger<GetPermissionsFromDatabaseTreeHandler> logger,IBaseRepository<PermissionModel> permissionRepo,IMapper mapper)
        {
            _logger = logger;
            this.permissionRepo = permissionRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 处理获取权限树请求
        /// </summary>
        /// <param name="request">权限命令</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回同意包装类</returns>
        public async Task<ApiResult<List<PermissionTreeDTO>>> Handle(GetPermissionsFromDatabaseTreeCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 模拟从数据库获取数据
                var permissions = GetPermissionsFromDatabase(0);
                return new ApiResult<List<PermissionTreeDTO>> { Code= ApiEnum.Success,Msg = "成功获取树形结构数据",Data = permissions };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取权限树形结构数据时发生异常，父级ID: {ParentId}", 0);
                return new ApiResult<List<PermissionTreeDTO>> { Code = ApiEnum.Error, Msg = "查询权限数据失败" };
            }
        }

        /// <summary>
        /// 模拟从数据库获取权限数据
        /// 实际项目中应该从数据库查询
        /// </summary>
        /// <returns>权限列表</returns>
        private List<PermissionTreeDTO> GetPermissionsFromDatabase(long id)
        {
            try
            {
                //从数据库中获取权限数据
                var resdata = permissionRepo.GetAll().Where(x => !x.IsDeleted && x.ParentId == id);
                //映射为DTO
                var model = mapper.Map<List<PermissionTreeDTO>>(resdata.ToList());
                //递归获取子权限
                foreach (var item in model)
                {
                    item.Children = GetPermissionsFromDatabase(item.Id);
                }
                return model;
            }
            catch (Exception)
            {
                // 处理异常
                throw;
            }
        }

    }
}
